<template>
  <div class="help-admin">
    <h2>💬 <span>帮助中心回复管理</span></h2>
    <div class="help-list">
      <div v-if="helpList.length === 0" style="color:#bbb;text-align:center;margin:32px 0;">暂无用户消息</div>
      <div v-for="item in helpList" :key="item.userId" class="help-item" @click="openChat(item.userId)">
        <span>用户ID: {{ item.userId }}</span>
        <span style="color:#888;font-size:0.95rem;">{{ item.lastMsg }}</span>
      </div>
    </div>
    <button class="q-btn" @click="replyHelp">回复问题</button>
    <div v-if="showChat" class="chat-modal">
      <div class="chat-header">
        <span>与用户 {{ currentUser }} 聊天</span>
        <button @click="closeChat">关闭</button>
      </div>
      <div class="chat-messages wechat-chat" ref="chatMsgBox">
        <div v-for="(msg, idx) in chatMessages" :key="idx" :class="['msg-row', msg.sender === 'agent' ? 'right' : 'left']">
          <div class="avatar">
            <img :src="msg.sender === 'agent' ? agentAvatar : (msg.avatar || userAvatar)" />
          </div>
          <div class="msg-content">
            <div class="nickname">{{ msg.sender === 'agent' ? '客服' : (msg.nickname || ('用户' + currentUser)) }}</div>
            <div class="msg-bubble" :class="msg.sender === 'agent' ? 'bubble-agent' : 'bubble-user'">
              {{ msg.text }}
            </div>
          </div>
        </div>
      </div>
      <div class="chat-input">
        <input v-model="newMessage" @keyup.enter="sendMessage" placeholder="输入回复..." />
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';

const helpList = ref<any[]>([]); // 用户消息列表
const showChat = ref(false);
const currentUser = ref('');
const chatMessages = ref<any[]>([]);
const newMessage = ref('');
let ws: WebSocket | null = null;
let reconnectTimer: any = null;
const chatMsgBox = ref<HTMLElement|null>(null);
const agentAvatar = '/admin-avatar.png'; // 可换成实际客服头像
const userAvatar = '/user-avatar.png'; // 可换成实际用户头像

function connectWS() {
  ws = new WebSocket('ws://' + window.location.hostname + ':666/?token=' + (localStorage.getItem('token') || ''));
  ws.onopen = () => {
    // 连接后主动请求历史会话
    ws.send(JSON.stringify({ type: 'getHistoryUsers' }));
  };
  ws.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      // 新增：收到历史会话数据
      if (data.type === 'historyUsers' && Array.isArray(data.users)) {
        helpList.value = data.users;
        return;
      }
      // 原有：实时消息推送
      if (data.type && data.content) {
        let user = helpList.value.find(u => u.userId === data.from);
        if (!user) {
          helpList.value.push({ userId: data.from, lastMsg: data.content, history: [{ sender: 'user', text: data.content, nickname: data.nickname, avatar: data.avatar }] });
        } else {
          user.lastMsg = data.content;
          user.history = user.history || [];
          user.history.push({ sender: 'user', text: data.content, nickname: data.nickname, avatar: data.avatar });
        }
        if (showChat.value && data.from === currentUser.value) {
          chatMessages.value.push({ sender: 'user', text: data.content, nickname: data.nickname, avatar: data.avatar });
          nextTick(() => scrollToBottom());
        }
      }
    } catch (e) {}
  };
  ws.onclose = () => {
    reconnectTimer = setTimeout(connectWS, 2000);
  };
}
onMounted(() => {
  connectWS();
});
onUnmounted(() => {
  ws && ws.close();
  if (reconnectTimer) clearTimeout(reconnectTimer);
});

function openChat(userId: string) {
  currentUser.value = userId;
  showChat.value = true;
  // 展示历史消息
  const user = helpList.value.find(u => u.userId === userId);
  chatMessages.value = user && user.history ? [...user.history] : [];
  nextTick(() => scrollToBottom());
}
function closeChat() {
  showChat.value = false;
  currentUser.value = '';
  chatMessages.value = [];
}
function sendMessage() {
  if (newMessage.value.trim() && ws && ws.readyState === 1 && currentUser.value) {
    const msg = {
      type: 'info',
      content: newMessage.value,
      to: currentUser.value
    };
    ws.send(JSON.stringify(msg));
    chatMessages.value.push({ sender: 'agent', text: newMessage.value });
    // 同步到helpList的history
    const user = helpList.value.find(u => u.userId === currentUser.value);
    if (user) {
      user.history = user.history || [];
      user.history.push({ sender: 'agent', text: newMessage.value });
      user.lastMsg = newMessage.value;
    }
    newMessage.value = '';
    nextTick(() => scrollToBottom());
  }
}
function scrollToBottom() {
  if (chatMsgBox.value) {
    chatMsgBox.value.scrollTop = chatMsgBox.value.scrollHeight;
  }
}
function replyHelp() {
  alert('请点击左侧用户进行对话回复');
}
</script>
<style scoped>
.help-admin {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 40px;
}
h2 {
  font-size: 2.2rem;
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  color: #2563eb;
  margin-bottom: 32px;
  text-shadow: 1px 2px 8px #e3edfa;
  display: flex;
  align-items: center;
  gap: 10px;
}
.q-btn {
  margin-top: 24px;
  background: linear-gradient(90deg, #e3edfa 0%, #2563eb 100%);
  color: #fff;
  border: none;
  border-radius: 14px;
  padding: 12px 32px;
  font-size: 1.1rem;
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  box-shadow: 0 4px 16px 0 rgba(120, 160, 255, 0.10);
  cursor: pointer;
  transition: background 0.2s, transform 0.2s;
}
.q-btn:hover {
  background: linear-gradient(90deg, #2563eb 0%, #e3edfa 100%);
  color: #2563eb;
  transform: scale(1.04);
}
.help-item {
  padding: 12px 18px;
  border-bottom: 1px solid #e3edfa;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: background 0.18s;
}
.help-item:hover {
  background: #f6faff;
}
.chat-modal {
  position: fixed;
  left: 0; right: 0; top: 0; bottom: 0;
  background: rgba(0,0,0,0.12);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
.chat-header {
  background: #fafdff;
  padding: 16px 24px;
  border-radius: 16px 16px 0 0;
  font-weight: bold;
  color: #2563eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chat-messages.wechat-chat {
  background: #e5ddd5;
  min-width: 340px;
  min-height: 320px;
  max-height: 420px;
  overflow-y: auto;
  padding: 24px 18px 18px 18px;
  display: flex;
  flex-direction: column;
}
.msg-row {
  display: flex;
  align-items: flex-end;
  margin-bottom: 18px;
}
.msg-row.left {
  flex-direction: row;
  justify-content: flex-start;
}
.msg-row.right {
  flex-direction: row-reverse;
  justify-content: flex-end;
}
.avatar {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  overflow: hidden;
  margin: 0 10px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.msg-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  max-width: 220px;
}
.msg-row.right .msg-content {
  align-items: flex-end;
}
.nickname {
  font-size: 13px;
  color: #888;
  margin-bottom: 2px;
}
.msg-bubble {
  padding: 10px 16px;
  border-radius: 18px;
  font-size: 15px;
  line-height: 1.5;
  word-break: break-all;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
.bubble-user {
  background: #fff;
  color: #222;
  border: 1.5px solid #e3edfa;
}
.bubble-agent {
  background: #95ec69;
  color: #222;
  border: 1.5px solid #b2e59e;
}
.chat-input {
  background: #fafdff;
  padding: 12px 24px;
  border-radius: 0 0 16px 16px;
  display: flex;
  gap: 12px;
}
.chat-input input {
  flex: 1;
  border-radius: 8px;
  border: 1.5px solid #e3edfa;
  padding: 10px 16px;
  font-size: 1rem;
}
.chat-input button {
  background: #2563eb;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 10px 24px;
  font-size: 1rem;
  cursor: pointer;
  transition: background 0.2s;
}
.chat-input button:hover {
  background: #165DFF;
}
</style>
